package com.ericpol.selenium;

import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertTrue;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class Page {

	protected WebDriver driver;

	public Page() {
		super();
	}

	@BeforeMethod
	public void setUp() throws Exception {
		driver = selectDriver("HtmlUnitDriver");
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	}

	@AfterMethod
	public void tearDown() throws Exception {
		driver.quit();

	}

	public WebDriver selectDriver(String drivername) {
		if (drivername.equals("InternetExplorer")) {
			return new InternetExplorerDriver();
		} else if (drivername.equals("HtmlUnitDriver")) {
			return new HtmlUnitDriver();
		}
		driver = new FirefoxDriver();
		return driver;
	}

	protected void assertText(String text) {
		assertEquals(text, driver.findElement(By.linkText(text)).getText());
	}

	protected boolean isTextOnPage(String expected) {

		boolean result = driver.getPageSource().contains(expected);
		return result;
	}

	protected void assertTextPresent(String expected) {
		boolean result = driver.getPageSource().contains(expected);
		assertTrue(result);
	}

	protected void click(By by) {
		driver.findElement(by).click();
	}

	protected void open(String urladdress) {
		driver.get(urladdress);
	}

	protected void insertText(By by, String text) {
		WebElement element = driver.findElement(by);
		element.clear();
		element.sendKeys(text);
	}
}